package record

import (
	"time"

	confv1beta1 "gopkg.openfuyao.cn/bkecommon/cluster/api/v1beta1"
	"sigs.k8s.io/controller-runtime/pkg/client"

	bkemetrics "gopkg.openfuyao.cn/cluster-api-provider-bke/pkg/metrics"
	"gopkg.openfuyao.cn/cluster-api-provider-bke/pkg/phaseframe/phaseutil"
	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils"
	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils/config"
	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils/log"
)

func NodeBootstrapFailedCountRecord(obj client.Object) {
	if config.MetricsAddr == "0" {
		return
	}
	bkemetrics.MetricRegister.RecordCounterVec(
		bkemetrics.NodeBootstrapFailedCount,
		utils.ClientObjNS(obj),
	).Inc()

}

func NodeBootstrapSuccessCountRecord(obj client.Object) {
	if config.MetricsAddr == "0" {
		return
	}
	bkemetrics.MetricRegister.RecordCounterVec(
		bkemetrics.NodeBootstrapSuccessCount,
		utils.ClientObjNS(obj),
	).Inc()
}

func NodeBootstrapDurationRecord(obj client.Object, node confv1beta1.Node, startTime time.Time, info string) {
	if config.MetricsAddr == "0" {
		return
	}

	key := utils.ClientObjNS(obj)

	bkemetrics.MetricRegister.RecordGaugeVec(
		bkemetrics.NodeBootstrapDurationSeconds,
		key,
		phaseutil.NodeInfo(node),
		phaseutil.NodeRoleString(node),
		info,
		bkemetrics.FormatTime(startTime),
		bkemetrics.TimeNow(),
	).Set(time.Since(startTime).Seconds())

	if config.E2EMode {
		if err := bkemetrics.MetricRegister.E2EDataGather(key); err != nil {
			log.Errorf("e2e mode enabled, but failed to save metrics data: %v", err)
			return
		}
	}

}
